from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from slewing.extension import db


# class Admin(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     username = db.Column(db.String(20))
#     password_hash = db.Column(db.String(128))


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    password_hash = db.Column(db.String(128))
    dev = db.relationship('Dev')  # 定义关系

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)


class Dev(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    # 用户绑定设备时上报
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 定义外键
    mac = db.Column(db.String(12), unique=True, nullable=False)
    # 节点与网关之间的距离，由后端计算
    d1 = db.Column(db.Float)
    d2 = db.Column(db.Float)
    d3 = db.Column(db.Float)
    # 网关的相对地理位置
    gateway1 = (0.7, 0)
    gateway2 = (1.1, 6.5)
    gateway3 = (3.7, 0)

    @staticmethod
    # def set_distance(rssi, a=52.17735818051857, n=2.5391991612141545):
    def set_distance(rssi, a=27.774202077130763, n=4.5364286572570895):
        return round(pow(10, float((abs(rssi) - a) / (10 * n))), 2)
